import React, {useEffect, useState} from "react";
import {
    ArticleControllerService,
    ArticleTinyVo,
    FriendShipControllerService,
    FriendVo,
    Permissions
} from "../../service";
import {
    Avatar, Button, ButtonGroup,
    List,
    Pagination, Popconfirm, SideSheet,
    Skeleton, Tag,
    Toast, Form, Space
} from "@douyinfe/semi-ui";
import {Link, useNavigate} from "react-router-dom";
import {AvatarColor} from "@douyinfe/semi-ui/lib/es/avatar";
//@ts-ignore
const renderMultipleWithCustomTag = (optionNode, {onClose}) => {
    const content = (
        <Tag avatarSrc={optionNode.userAvatar} avatarShape="circle" closable={true} onClose={onClose} size="large">
            {optionNode.userName}
        </Tag>
    );
    return {
        isRenderInTag: false,
        content,
    };
};

const renderCustomOption = (item: FriendVo) => {
    const {Option} = Form.Select;
    const optionStyle = {
        display: 'flex',
        paddingLeft: 24,
        paddingTop: 10,
        paddingBottom: 10,
    };
    return (
        <Option value={item.id} style={optionStyle} showTick={true} {...item} key={item.id}>
            <Avatar size="small" src={item.userAvatar}/>
            <div style={{marginLeft: 8}}>
                <div style={{fontSize: 14}}>{item.userName}</div>
                <div
                    style={{color: 'var(--color-text-2)', fontSize: 12, lineHeight: '16px', fontWeight: 'normal'}}
                >
                    {item.userName}
                </div>
            </div>
        </Option>
    );
};
const placeholder = (
    <div
        style={{
            display: 'flex',
            alignItems: 'flex-start',
            padding: 12,
            borderBottom: '1px solid var(--semi-color-border)',
        }}
    >
        <Skeleton.Avatar style={{marginRight: 12}}/>
        <div>
            <Skeleton.Title style={{width: 120, marginBottom: 12, marginTop: 12}}/>
            <Skeleton.Paragraph style={{width: 600}} rows={2}/>
        </div>
    </div>
);
const MineArticleView: React.FC = () => {

    const handleDelete = async (id: number) => {
        const res = await ArticleControllerService.removeArticlesById([id]);
        if (res.code !== 200) {
            Toast.error("删除失败:" + res.message)
            return;
        }
        Toast.info({content: "删除成功"});
    }
    const loadPermissions = async (item: ArticleTinyVo) => {
        setSelectedItem(item);
        const res = await ArticleControllerService.getPermissionById({id: item.id});
        if (res.code !== 200) {
            return
        }
        setPermissions(res.data)
        setVisible(true);
    }
    const getFormApi = (formapi: object) => {
        setFormApi(formapi);
    }
    const updatePermission = async () => {
        const res = await ArticleControllerService.updatePermission({
            articleId: selectedItem?.id || 0,
            //@ts-ignore
            permissions: formApi.getValues(),
        })
        if (res.code !== 200) {
            Toast.error("操作失败:" + res.message)
            return;
        }
        Toast.info({content: "修改成功"});
        setVisible(false);
    }
    const [page, setPage] = useState(0);
    const [total, setTotal] = useState(0);
    const [friendList, setFriendList] = useState<FriendVo[]>([]);
    const [formApi, setFormApi] = useState<object>();

    const navigate = useNavigate();
    const [permissions, setPermissions] = useState<Permissions>()
    const [visible, setVisible] = useState(false);
    const [selectedItem, setSelectedItem] = useState<ArticleTinyVo>();
    const pageSize = 10;
    const [dataList, setDataList] = useState<ArticleTinyVo[]>([]);
    const loadData = async (currentPage: number) => {
        setPage(currentPage);
        const res = await ArticleControllerService.articleOwnTinyVoListByPage({
            page: currentPage,
            pageSize: pageSize,
        });
        if (!res.data) {
            Toast.error("数据加载失败:" + res.message);
            return;
        }
        setTotal(res.data.total || 0);
        const data = res?.data?.records ?? [];
        if (data.length === 0) {
            Toast.info({content: "没有更多了"});
        }
        setDataList(data);

    }
    const loadFriendList = async () => {
        const res = await FriendShipControllerService.selectFriend()
        if (res.code != 200) {
            Toast.error("数据加载失败:" + res.message)
            return;
        }
        setFriendList(res.data || []);
    }
    useEffect(() => {
        loadData(1);
        loadFriendList();
    }, [])
    return (
        <div>
            <List
                loading={false}
                dataSource={dataList}
                renderItem={(item) => {
                    let color: AvatarColor;
                    let header;
                    if (item.type == "Markdown") {
                        color = "blue";
                        header = "Md";
                    } else if (item.type === "Slate") {
                        color = "yellow";
                        header = "Slate";
                    }

                    return (
                        <Skeleton placeholder={placeholder} loading={false}>
                            <List.Item
                                // @ts-ignore
                                header={<Avatar color={color}>{header}</Avatar>}
                                main={
                                    <Link to={'/view/md?id=' + item.id} style={{textDecoration: "none"}}>
                                        <div>
                                    <span style={{color: 'var(--semi-color-text-0)', fontWeight: 500}}>
                                        {item.title}{item?.permissions?.collaborative && <Tag>协作中</Tag>}
                                    </span>

                                            <p style={{color: 'var(--semi-color-text-2)', margin: '4px 0'}}>
                                                {item.description}
                                            </p>
                                        </div>
                                    </Link>

                                }
                                extra={
                                    <ButtonGroup theme="borderless">
                                        <Button onClick={() => {
                                            let url;
                                            if (item.type === "Slate") {
                                                url = "/edit/slate/update?id=";
                                                if(item?.permissions?.collaborative){
                                                    url="/edit/slate/update/collaboration?articleId="
                                                }
                                            } else if (item.type === "Markdown") {
                                                url = "/edit/md/update?id="
                                            }
                                            navigate(url +"" + item.id);
                                        }
                                        }>编辑</Button>
                                        {item.type === "Slate" && <Button onClick={
                                            () => {
                                                loadPermissions(item)
                                            }
                                        }
                                        >协作</Button>}
                                        <Popconfirm

                                            title="确定是否要删除该文章？"
                                            content="此操作将不可逆"
                                            position={'leftTop'}
                                            onConfirm={() => {
                                                handleDelete(item.id || 0);
                                                loadData(page);
                                            }
                                            }>
                                            <Button>删除</Button>
                                        </Popconfirm>

                                    </ButtonGroup>}
                            />
                        </Skeleton>
                    )
                }}

            />
            <Pagination style={{width: '100%', flexBasis: '100%', justifyContent: 'center'}}
                        pageSize={pageSize} total={total} currentPage={page}
                        onChange={loadData}/>
            <SideSheet title="协作权限设置" visible={visible}
                       onCancel={() => {
                           setVisible(!visible);
                       }} size={"small"}>
                <Form getFormApi={getFormApi}
                      initValues={{
                          'collaborative': permissions?.collaborative,
                          'collaborators': permissions?.collaborators,
                      }}
                >
                    <Form.Switch field={'collaborative'} label={'开启协作'}/>
                    <Form.Select
                        field={'collaborators'}
                        label={'权限列表'}
                        placeholder="请选择"
                        maxTagCount={2}
                        style={{width: 280, marginTop: 20}}
                        onChange={(value) => {
                            // console.log(value)
                        }}
                        multiple
                        renderSelectedItem={renderMultipleWithCustomTag}
                    >
                        {friendList.map((item) => renderCustomOption(item))}
                    </Form.Select>
                </Form>
                <Space spacing={"loose"}>
                    {/*<Button onClick={() => {*/}

                    {/*}}>编辑</Button>*/}

                    <Button onClick={updatePermission}>提交</Button>
                </Space>


            </SideSheet>
        </div>
    )
}
export default MineArticleView;
